package com.yangj.servlet;

import javax.servlet.http.*;
import com.yangj.service.*;
import javax.servlet.*;
import java.io.*;
import java.util.*;

public class WeChatTestServlet extends HttpServlet
{
    protected void doGet(final HttpServletRequest req, final HttpServletResponse resp) throws ServletException, IOException {
    	//微信通过get发送请求过来
    	System.out.println("wexin get");
/*		signature	微信加密签名，signature结合了开发者填写的token参数和请求中的timestamp参数、nonce参数。
		timestamp	时间戳
		nonce	随机数
		echostr	随机字符串*/
        final String signature = req.getParameter("signature");
        final String timestamp = req.getParameter("timestamp");
        final String nonce = req.getParameter("nonce");
        final String echostr = req.getParameter("echostr");
        System.out.println(signature);
        System.out.println(timestamp);
        System.out.println(nonce);
        System.out.println(echostr);
        
/*		开发者通过检验signature对请求进行校验（下面有校验方式）。
		若确认此次GET请求来自微信服务器，请原样返回echostr参数内容，则接入生效，成为开发者成功，否则接入失败。加密/校验流程如下：
		*/
        final WeChatVerifyService ws = new WeChatVerifyService();
        if (WeChatVerifyService.check(timestamp, nonce, signature)) {
            System.out.println("接入成功");
            final PrintWriter out = resp.getWriter();
            out.print(echostr);
            out.flush();
            out.close();
        }
        else {
            System.out.println("接入失败");
        }
    }
    
    protected void doPost(final HttpServletRequest req, final HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");
        //处理消息和事件推送
        Map<String, String> requestMap = WeChatVerifyService.parseRequest((InputStream)req.getInputStream());
        System.out.println(requestMap);
//		准备回复的数据包
        String respXml = WeChatVerifyService.getResponse(requestMap);
        System.out.println("servlet: " + respXml);
        PrintWriter out = resp.getWriter();
        out.print(respXml);
        out.flush();
        out.close();
    }
}
